<?php

namespace Home\Controller;
use Think\Controller;
use User\Api\UserApi;

/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class HomeController extends Controller {
    //微信配置
    protected $appid = "wxecc4a9c96bce4b55";
    protected $secret = "63c1208cd5f50d2a29f552a8d853696c";

	/* 空操作，用于输出404页面 */
	public function _empty(){
		$this->redirect('Index/index');
	}


    protected function _initialize(){
        /* 读取站点配置 */
        $config = api('Config/lists');
        C($config); //添加配置

        if(!C('WEB_SITE_CLOSE')){
            $this->error('站点已经关闭，请稍后访问~');
        }


        //获取微信openId
        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') && !is_login()){
//            $openId = $this->getopenid();
//            if (!empty($openId)) {
//                $user = M('ucenter_member')->where(["wx_open_id"=>$openId])->find();
//                if (empty($user)) {
////                    //无账号，注册
//
//                     //微信注册信息
//
//                    $ucenter_data = [
//                        "username"=>"wx_user_".time(),
//                        "wx_open_id"=>$openId,
//                        "status"=>1
//                    ];
//                    $uid = M('ucenter_member')->add($ucenter_data);
//                    $data = array(); // member注册数据
//                    $data['uid'] = $uid;
//                    $data['nickname'] = "微信用户".time();
//                    $data['status'] = 1;
//
//                    if ($uid > 0) { //注册成功
//                        M('Member')->add($data); // 添加注册数据
//                        //TODO: 发送验证邮件
//                        action_log('user_register', 'member', $uid, $uid, array('score'=>100));     // 用户增加积分
//                    } else { //注册失败，显示错误信息
//                       $this->error("微信登录失败");
//                    }
//                } else {
//                    $uid = $user["id"];
//                }
//                D('Member')->login($uid);
//            }else {
//                $this->error("没有获取到授权");
//            }
        }
        define('UID', is_login());  // 当前用户id
    }

	/* 用户登录检测 */
	protected function checkLogin(){
		/* 用户登录检测 */
		is_login() || $this->error('您还没有登录，请先登录！', U('User/login'));
	}


    /**
     * 获取分类树所有分类id
     * @param $cate
     * @param string $returnType
     * @return array|string
     */
    protected function getTreeToCateIdStr($cate, $returnType="string")
    {
        $result = array();
        $cateList = tree_to_list(array($cate));
        foreach($cateList as $cate){
            $result[] = $cate['id'];
        }
        switch($returnType){
            case 'string':
                return implode(',', $result);
            default:
                return $result;
        }
    }

    /**
     * 上传单个文件
     * @param string $image
     * @param bool|false $isImg true时是$_FILES数据, false时是图片文件元素名称
     * @return string
     */
    protected function _upload($image='img', $isImg=false) {
        header("Content-Type:text/html;charset=utf-8");
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg','gif','png','jpeg');// 设置附件上传类
        $upload->savePath  =      'Images/'; // 设置附件上传目录
        // 上传文件
        if(!$isImg){
            $image = $_FILES[$image];
        }
        $info   =   $upload->uploadOne($image);

        if(!$info) {// 上传错误提示错误信息
            throw new \Exception($upload->getError());
        }
        return  $upload->rootPath.$info['savepath'].$info['savename'];

    }

    //----------------------------------微信-----------------------------------------------------
    //获取微信openid
    public function getopenid()
    {
        //通过code获得openid
        if (!$_GET['code']){
            $this->getwxcode();
        } else {
            //获取code码，以获取openid
            $code = $_GET['code'];
            $openid = $this->GetOpenidFromMp($code);
            //刷新页面之后要重新获取code
            if(!$openid){
                $this->getwxcode();
            }
            return $openid;
        }
    }

    //触发微信返回code码(只能用一次)
    public function getwxcode(){
        $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        $url = $this->__CreateOauthUrlForCode($baseUrl);
        Header("Location: $url");
        exit();
    }
    public function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        // $urlObj["scope"] = "snsapi_base";//静默授权
        $urlObj["scope"] = "snsapi_userinfo";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);

        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        // if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
        //     && WxPayConfig::CURL_PROXY_PORT != 0){
        //     curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
        //     curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
        // }
        //运行curl，结果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res,true);
        $this->data = $data;
        $openid = $data['openid'];
        return $openid;
    }
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["secret"] = $this->secret;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
}
